package LeetCode;

import java.math.BigInteger;

/**
 * @Author Kechelle
 * @Date 2020/9/11 23:26
 * @Version 1.0
 */
public class Code67 {
    public static String addBinary(String a, String b) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        StringBuffer sb = new StringBuffer();
        //保存进位
        int carry = 0;
        //都从最后一位开始算起，只要没有遍历完就累加
        while (i>=0 || j>=0 || carry>0){
            int x = (i>=0) ? a.charAt(i) - '0' : 0;
            int y = (j>=0) ? b.charAt(j) - '0' : 0;
            int sum = x + y + carry;
            sb.append(sum%2);
            carry = sum/2;
            i--;
            j--;
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        System.out.println(addBinary("1010","1011"));
    }


    //BigInteger解法
    /*
    BigInteger aNum = new BigInteger(a,2);
        BigInteger bNum = new BigInteger(b,2);
        BigInteger ans = aNum.add(bNum);
        String str = ans.toString(2);
        return str;
     */
}
